package com.linzm.leetcode.primary.exercises3_20230122;

/**
 * @Author zimingl
 * @Date 2023/1/22 0:37
 * @Description: 七进制数
 */
public class Demo1_504 {
    /**
     * 给定一个整数 num，将其转化为 7 进制，并以字符串形式输出。
     */
    public static void main(String[] args) {
        Demo1_504 demo1_504 = new Demo1_504();
//        int num = -100;
        int num = -7;
        String convertToBase7 = demo1_504.convertToBase72(num);
        System.out.println(convertToBase7);
    }

    private String convertToBase7(int num) {
        return Integer.toString(num, 7);
    }

    private String convertToBase72(int num) {
        if (num == 0) {
            return "0";
        }
        boolean flag = false;
        if (num < 0) {
            flag = true;
            num = -num;
        }
        int[] arr = new int[8];
        arr[7] = 1;
        for (int i = 6; i >= 0; i--) {
            arr[i] = arr[i + 1] * 7;
        }
        int[] resArr = new int[8];
        for (int i = 0; i < arr.length; i++) {
            if (num >= arr[i]) {
                int tmp = num / arr[i];
                resArr[i] = tmp;
                num -= tmp * arr[i];
            }
        }
        String res = "";
        for (int i = 0; i < resArr.length; i++) {
            if (resArr[i] == 0 && !res.equals("")) {
                res = res + "0";
            }
            if (resArr[i] != 0) {
                res += resArr[i];
            }
        }
        if (flag) {
            res = "-" + res;
        }
        return res;
    }

    public String convertToBase73(int num) {
        boolean flag = false;
        if (num < 0) {
            flag = true;
            num = -num;
        }
        int[] arr = new int[8];
        arr[7] = 1;
        for (int i = 6; i >= 0; i--) {
            arr[i] = arr[i + 1] * 7;
        }
        String res = "";
        for (int i = 0; i < arr.length; i++) {
            if (num < arr[i] && !res.equals("") && num / arr[i] < 1) {
                res += "0";
            }
            if (num >= arr[i]) {
                int tmp = num / arr[i];
                res += tmp;
                num -= tmp * arr[i];
            }
        }
        if (flag) {
            res = "-" + res;
        }
        return res;
    }
}

